<template>
  <div>
    <!-- 退货管理 -->
    <el-table-form :inline="true" :model="query" class="demo-form">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 180px; margin-right: 2px;">
          <el-option label="单据号" value="billCode" />
          <el-option label="联系电话" value="csmPhone" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="地址" value="csmAddress" />
          <el-option label="关联订单号" value="orderCode" />
        </el-select>
        <el-input v-model="csmText" placeholder="请输入内容" clearable />
      </el-form-item>
      <el-form-item label="商品:">
        <el-select v-model="query.goodsId" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in goodsList"
            :key="item.goodsId"
            :label="item.goodsName"
            :value="item.goodsId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退货单位:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
      </el-form-item>
      <el-form-item :table-form-merge="2" label="退货日期:">
        <el-date-picker v-model="date" type="daterange" :clearable="false" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.orderStatusSource" clearable placeholder="请选择">
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 查询按钮 -->
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <!-- 导出按钮 -->
    <div class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-folder-opened" style="margin-bottom: 20px;">导出</el-button>
      </div>
    </div>
    <!-- 表单 -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <returnOfTheAudit ref="returnOfTheAudit" @del="del" />
  </div>
</template>

<script>
  import { queryRefundOrderTableList, queryGasGoodsListAll, queryMap, returnGoodsOrderDelete } from '@/api'
  import ReturnOfTheAudit from './components/ReturnOfTheAudit'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'refundsManage',
    components: {
      ReturnOfTheAudit
    },
    data() {
      return {
        actionColWidth: 80,
        csmType: 'csmPhone',
        csmText: '',
        date: [moment().subtract(1, 'days').startOf('day'), moment().endOf('day')],
        query: {
          goodsId: '',
          orgSNNo: '',
          roleType: ''
        },
        goodsList: [],
        treeData: [],
        billStatusMap: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'billCode',
            label: '单据号',
            width: 150,
            render: (h, { row }) => <el-link onClick={() => this.openSalesReturnDetails(row)}>{row.billCode}</el-link>
          },
          {
            prop: 'orderCode',
            width: 100,
            label: '关联订单号'
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 110
          },
          {
            prop: 'csmPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 200
          },
          {
            prop: 'orgName',
            label: '退货单位',
            width: 160
          },
          {
            prop: 'operator',
            label: '退货人'
          },
          {
            prop: 'createUser',
            label: '经办人'
          },
          {
            prop: 'returnTime',
            width: 150,
            label: '退货时间',
            render: (h, { row }) => <span>{ row.returnTime && parseTime(row.returnTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'remark',
            label: '退货原因'
          },
          {
            prop: 'billStatus',
            label: '单据状态',
            render: (h, { row }) => <span>{ row.billStatus && formatColumnMap(this.billStatusMap, 'value', row.orderStatus, 'desc') }</span>
          },
          {
            prop: 'auditTime',
            width: 150,
            label: '审核日期',
            render: (h, { row }) => <span>{ row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            label: '操作',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.billStatus === 1 && <el-link size='mini' onClick={() => this.openReturnOfTheAudit(row, $index)}>
                    审核
                  </el-link>}
                  {row.billStatus !== -1 && <el-link size='mini' type='danger' onClick={() => this.del(row, $index)}>
                    作废
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getGoodsListAll()])
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.startDt = moment(this.date[0]).format()
          query.endDt = moment(this.date[1]).format()
        }
        query[this.csmType] = this.csmText
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 366) {
          this.$message.warning('退货日期最大支持查询1年')
          return
        }
        const res = await queryRefundOrderTableList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取所有商品列表
      async getGoodsListAll() {
        const res = await queryGasGoodsListAll()
        this.goodsList = res.data
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' })
        this.billStatusMap = res.data // 订单类型
      },
      // 订单号
      async openSalesReturnDetails(row) {
        await this.$refs.returnOfTheAudit.open(row, 'detail')
      },
      // 审核
      async openReturnOfTheAudit(row) {
        await this.$refs.returnOfTheAudit.open(row, 'audit')
        this.$refs.lbTable.fetch()
      },
      // 作废
      del(row, index) {
        this.$confirm('确认要作废该退货单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          returnGoodsOrderDelete({ billCode: row.billCode }).then(() => {
            this.tableData.data.splice(index, 1)
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .btn-group {
    display: flex;
    justify-content: space-between;
  }
</style>
